package com.mall.mina.config;

import com.mall.mina.util.AgreementConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

import java.nio.charset.Charset;

/**
 * describe 自定义编码器
 */
@Slf4j
public class CustomProtocolEncoder implements ProtocolEncoder {

    private final Charset charset;

    public CustomProtocolEncoder() {
        this.charset = Charset.defaultCharset();
    }

    // 构造方法注入编码格式
    public CustomProtocolEncoder(Charset charset) {
        this.charset = charset;
    }

    @Override
    public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
        // 转为自定义协议包
        CustomPack pack = (CustomPack) message;
        // 初始化缓冲区
        IoBuffer buffer = IoBuffer.allocate(message.toString().getBytes().length)
                .setAutoExpand(true);

        //设置帧长度
        buffer.put(pack.getLen());

        //设置操作码 + 负载
        if (pack.getContent() != null) {
            buffer.put(pack.getContent());
        }
        //设置校验
        if (pack.getCrc() != null){
            buffer.put(pack.getCrc());
        }
        // 重置mask，发送buffer
        buffer.flip();
        out.write(buffer);
    }

    @Override
    public void dispose(IoSession session) throws Exception {

    }
}